package com.ctsi.organise.service;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.mybatis.support.MybatisBatchDao;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.organise.entity.PersonInfoNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangjw
 * @className ScheduledService
 * @description 人员图谱任务定时任务配置
 * @date 2019/3/30 16:31
 **/
@Component
@EnableScheduling
@Lazy(false)
public class ScheduledPersonInfoService {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledPersonInfoService.class);

    private static final int DEFAULT_PAGE = 50;

    @Autowired
    private MybatisGenericDao dao;

    @Autowired
    private MybatisBatchDao batchDao;

    /**
     * 聚合人员图谱信息，每天晚上11点开始聚合
     */
    //@Scheduled(cron = "0 */2 * * * ?")
    @Scheduled(cron = "0 57 2 * * ?")
    public void initPersonInfoNode(){
        logger.warn("================================================================================================");
        initData(0);
    }

    /**
     * 递归聚合数据
     * @param start
     */
    public void initData(int start){
        Page<Map<String,Object>> result = findSupports(start);
        if (UtilValidate.isNotEmpty(result.getResult())) {

            result.getResult().stream().forEach(map -> {
                String personId = (String) map.get("PARTYID");
                String personName = (String) map.get("FULLNAME");
                logger.warn("begin init person info for {}",personName);
                // 先删除该人员的所有信息
                dao.delete(PersonInfoNode.class.getName()+".deleteUserInfo",personId);
                List<PersonInfoNode> nodes = new ArrayList<>();
                // 人员信息
                PersonInfoNode root = new PersonInfoNode("root",null,personId,personName,"人员信息","",0L);
                nodes.add(root);
                // 业务支撑
                PersonInfoNode ywzc = new PersonInfoNode("ywzc","root",personId,personName,"业务支撑","",0L);
                nodes.add(ywzc);
                // 支撑能力
                PersonInfoNode zcnl = new PersonInfoNode("zcnl","root",personId,personName,"支撑能力","",1L);
                nodes.add(zcnl);
                // 岗位工作
                PersonInfoNode gwgz = new PersonInfoNode("gwgz","root",personId,personName,"岗位工作","",2L);
                nodes.add(gwgz);
                // 基本信息
                PersonInfoNode jbxx = new PersonInfoNode("jbxx","root",personId,personName,"基本信息","",3L);
                nodes.add(jbxx);
                // 认证培训
                PersonInfoNode rzpx = new PersonInfoNode("rzpx","root",personId,personName,"认证与培训","",4L);
                nodes.add(rzpx);
                // 派单支撑
                PersonInfoNode pdzc = new PersonInfoNode("pdzc","ywzc",personId,personName,"派单支撑","",0L);
                nodes.add(pdzc);
                // 问题解答数量
                Long count = (Long) dao.queryForObject(PersonInfoNode.class.getName()+".queryAnswerTimes",personId);
                PersonInfoNode wtjdsl = new PersonInfoNode("wtjdsl","ywzc",personId,personName,"问题解答数量:",String.valueOf(count),1L);
                nodes.add(wtjdsl);
                // 案例分享
                //PersonInfoNode alfx = new PersonInfoNode("alfx","ywzc",personId,personName,"案例分享",null,0);

                Map<String,Object> supportInfo = (Map<String, Object>) dao.queryForObject(PersonInfoNode.class.getName()+".querySupportInfo",personId);
                // 支撑项目数量
                PersonInfoNode zcxmsl = new PersonInfoNode("zcxmsl","pdzc",personId,personName,"支撑项目数量:",  String.valueOf(supportInfo.get("SUPPORTPROJECTCOUNT")),0L);
                nodes.add(zcxmsl);
                // 签约项目数量
                PersonInfoNode qyxmsl = new PersonInfoNode("qyxmsl","pdzc",personId,personName,"签约项目数量:", String.valueOf(supportInfo.get("SIGNPROJECTCOUNT")) ,1L);
                nodes.add(qyxmsl);
                // 支撑工作量
                PersonInfoNode zcgzl = new PersonInfoNode("zcgzl","pdzc",personId,personName,"支撑工作量:", String.valueOf(supportInfo.get("WORKLOAD")) ,2L);
                nodes.add(zcgzl);
                // 支撑满意度
                PersonInfoNode zcmyd = new PersonInfoNode("zcmyd","pdzc",personId,personName,"支撑满意度:", String.valueOf(supportInfo.get("MANYIDU")) ,3L);
                nodes.add(zcmyd);

                List<Map<String,String>> sss = (List<Map<String, String>>) dao.queryForList(PersonInfoNode.class.getName()+".querySupportTypeInfo",personId);
                sss.stream().forEach(s -> {
                    int index = sss.indexOf(s);
                    nodes.add( new PersonInfoNode("zcxmsl"+ index,"zcxmsl",personId,personName,s.get("SUPPORTTYPENAME")+"数量:", String.valueOf(s.get("SUPPORTTYPECOUNT")) ,(long)index));
                });

                // 组装支撑能力
                List<Map<String,Object>> as = (List<Map<String, Object>>) dao.queryForList(PersonInfoNode.class.getName()+".queryAbility",personId);
                as.stream().forEach(a -> {
                    String id = (String) a.get("ID");
                    String parentId = (String) a.get("PARENTID");
                    if ("root".equals(parentId)) {
                        nodes.add(new PersonInfoNode(id,"zcnl",personId,personName,(String)a.get("ABILITY"), "",(long) a.get("ORDERNO")));
                    } else {
                        nodes.add(new PersonInfoNode(id,parentId,personId,personName,(String)a.get("ABILITY"), "",(long)a.get("ORDERNO")));
                    }
                });
                // 组装岗位工作
                List<Map<String,String>> gws = (List<Map<String, String>>) dao.queryForList(PersonInfoNode.class.getName()+".queryPersonGW",personId);
                gws.stream().forEach(g -> {
                    String gn = g.get("GWMC");
                    int i = gws.indexOf(g);
                    nodes.add(new PersonInfoNode("gwgz"+i,"gwgz",personId,personName,gn,"",(long)i));
                });

                Map<String,String> info = (Map<String, String>) dao.queryForObject(PersonInfoNode.class.getName()+".queryPersonBaseInfo",personId);
                // 姓名
                nodes.add(new PersonInfoNode("jbxx_"+"FULLNAME","jbxx",personId,personName,"姓名:",info.get("FULLNAME"),0l));
                // 性别
                nodes.add(new PersonInfoNode("jbxx_"+"GENDER","jbxx",personId,personName,"性别:",info.get("GENDER"),1l));
                // 联系方式
                nodes.add(new PersonInfoNode("jbxx_"+"MOBILEPHONE","jbxx",personId,personName,"联系方式:",info.get("MOBILEPHONE"),2l));
                // 年龄
                nodes.add(new PersonInfoNode("jbxx_"+"AGE","jbxx",personId,personName,"年龄:",info.get("AGE"),3l));
                // 工作年限
                nodes.add(new PersonInfoNode("jbxx_"+"GZNX","jbxx_"+"AGE",personId,personName,"工作年限:",info.get("GZNX"),4l));
                // 学历
                nodes.add(new PersonInfoNode("jbxx_"+"DEGREE","jbxx",personId,personName,"学历:",info.get("DEGREE"),4l));
                // 专业人才名称
                nodes.add(new PersonInfoNode("jbxx_"+"ZYRCMC","jbxx",personId,personName,"专业人才名称:",info.get("ZYRCMC"),5l));
                // 专业人才级别
                nodes.add(new PersonInfoNode("jbxx_"+"ZYRC","jbxx_"+"ZYRCMC",personId,personName,"专业人才级别:",info.get("ZYRC"),5l));
                // 用工形式
                nodes.add(new PersonInfoNode("jbxx_"+"YGXS","jbxx",personId,personName,"用工形式:",info.get("YGXS"),6l));
                // 技术专长
                nodes.add(new PersonInfoNode("jbxx_"+"JSZC","jbxx",personId,personName,"技术专长:",info.get("JSZC"),7l));
                // 岗级
                nodes.add(new PersonInfoNode("jbxx_"+"MQGJ","jbxx",personId,personName,"岗级:",info.get("MQGJ"),8l));
                // 工作经历
                //nodes.add(new PersonInfoNode("jbxx_"+"GZJL","jbxx",personId,personName,"工作经历:",info.get("GZJL"),9));

                // 培训
                //nodes.add(new PersonInfoNode("rzpx_PX","rzpx",personId,personName,"培训","",0));
                // 认证
                nodes.add(new PersonInfoNode("rzpx_RZ","rzpx",personId,personName,"认证","",1l));
                List<Map<String,Object>> rzs = (List<Map<String, Object>>) dao.queryForList(PersonInfoNode.class.getName()+".queryRZ",personId);
                Map<String,List<Map<String,Object>>> rzss = rzs.stream().collect(Collectors.groupingBy(rz -> (String) rz.get("RZLX")));
                rzss.keySet().stream().forEach(key -> {
                    String uuid = UUIDGenerator.getId();
                    nodes.add(new PersonInfoNode(uuid,"rzpx_RZ",personId,personName,key,"",1l));
                    rzss.get(key).stream().forEach(r -> {
                        StringBuilder sb = new StringBuilder((String) r.get("ZSMC"));
                        String jb = (String) r.get("RZJB");
                        if (UtilValidate.isNotEmpty(jb)) {
                            sb.append("(").append(jb).append(")");
                        }
                        nodes.add(new PersonInfoNode(UUIDGenerator.getId(),uuid,personId,personName,sb.toString(),"",1l));
                    });
                });

//                batchDao.batchInsert(PersonInfoNode.class,nodes);
                nodes.forEach(node -> dao.insert(node));
                logger.warn("end init person info for {}",personName);
            });
            // 继续执行
            initData(((int)result.getCurrentPageNo())*DEFAULT_PAGE);
        }
    }

    /**
     * 分页获取所有产品经理
     */
    public Page<Map<String,Object>> findSupports(int start){
        return dao.queryPage(PersonInfoNode.class.getName()+".querySupportUsers",null,start,DEFAULT_PAGE);
    }

}
